<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="BOM编码" prop="bomCode">
        <el-input v-model="queryParams.bomCode" placeholder="请输入BOM编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="BOM名称" prop="bomName">
        <el-input v-model="queryParams.bomName" placeholder="请输入BOM名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:bom:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['mes:bom:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:bom:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['mes:bom:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="BOM编码" align="center" prop="bomCode" />
      <el-table-column label="BOM名称" align="center" prop="bomName" />
      <el-table-column label="产品编码" align="center" prop="productCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="版本" align="center" prop="version" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:bom:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:bom:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改BOM主表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-tabs v-model="activeTab" type="card">
        <!-- BOM基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="BOM编码" prop="bomCode">
                  <el-input v-model="form.bomCode" placeholder="请输入BOM编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="BOM名称" prop="bomName">
                  <el-input v-model="form.bomName" placeholder="请输入BOM名称" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 产品选择器 -->
                <el-form-item label="产品选择" prop="productId">
                  <el-select v-model="form.productId" placeholder="请选择产品" clearable filterable @change="handleProductChange"
                    style="width: 100%">
                    <el-option v-for="material in materialList" :key="material.materialId"
                      :label="`${material.materialCode} - ${material.materialName}`" :value="material.materialId">
                      <span style="float: left">{{ material.materialCode }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ material.materialName }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="版本" prop="version">
                  <el-input v-model="form.version" placeholder="请输入版本" />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <!-- 产品编码改为只读 -->
                <el-form-item label="产品编码" prop="productCode">
                  <el-input v-model="form.productCode" placeholder="请选择产品后自动填充" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <!-- 产品名称改为只读 -->
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="form.productName" placeholder="请选择产品后自动填充" readonly />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                      :label="dict.value">{{ dict.label }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- BOM明细标签页 -->
        <el-tab-pane label="BOM明细" name="detail" :disabled="!form.bomId">
          <div style="margin-bottom: 10px;">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddDetail"
              v-hasPermi="['mes:bomDetail:add']">新增明细</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="detailMultiple" @click="handleDeleteDetail"
              v-hasPermi="['mes:bomDetail:remove']">删除明细</el-button>
          </div>
          
          <el-table :data="bomDetailList" @selection-change="handleDetailSelectionChange" border>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="物料编码" align="center" prop="materialCode" />
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="物料规格" align="center" prop="materialSpec" />
            <el-table-column label="单位" align="center" prop="materialUnit" />
            <el-table-column label="用量" align="center" prop="quantity" />
            <el-table-column label="排序" align="center" prop="sortNum" />
            <el-table-column label="操作" align="center" width="150">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateDetail(scope.row)"
                  v-hasPermi="['mes:bomDetail:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteDetail(scope.row)"
                  v-hasPermi="['mes:bomDetail:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- BOM明细添加/修改对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="600px" append-to-body>
      <el-form ref="detailForm" :model="detailForm" :rules="detailRules" label-width="80px">
        <el-form-item label="物料选择" prop="materialId">
          <el-select v-model="detailForm.materialId" placeholder="请选择物料" clearable filterable @change="handleDetailMaterialChange"
            style="width: 100%">
            <el-option v-for="material in materialList" :key="material.materialId"
              :label="`${material.materialCode} - ${material.materialName}`" :value="material.materialId">
              <span style="float: left">{{ material.materialCode }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ material.materialName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="detailForm.materialCode" placeholder="请选择物料后自动填充" readonly />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="detailForm.materialName" placeholder="请选择物料后自动填充" readonly />
        </el-form-item>
        <el-form-item label="物料规格" prop="materialSpec">
          <el-input v-model="detailForm.materialSpec" placeholder="请选择物料后自动填充" readonly />
        </el-form-item>
        <el-form-item label="单位" prop="materialUnit">
          <el-input v-model="detailForm.materialUnit" placeholder="请选择物料后自动填充" readonly />
        </el-form-item>
        <el-form-item label="用量" prop="quantity">
          <el-input-number v-model="detailForm.quantity" :precision="2" :min="0" placeholder="请输入用量" style="width: 100%" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input-number v-model="detailForm.sortNum" :min="0" placeholder="请输入排序" style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDetailForm">确 定</el-button>
        <el-button @click="cancelDetail">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom, checkBomCodeUnique } from "@/api/mes/basic/bom";
import { getBomDetailByBomId, addBomDetail, updateBomDetail, delBomDetail } from "@/api/mes/basic/bomDetail";
import { listMaterial } from "@/api/mes/basic/material";

export default {
  name: "Bom",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // BOM主表表格数据
      bomList: [],
      // 物料列表
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前激活的标签页
      activeTab: "basic",
      // BOM明细列表
      bomDetailList: [],
      // 明细选中数组
      detailIds: [],
      // 明细非多个禁用
      detailMultiple: true,
      // 明细弹出层标题
      detailTitle: "",
      // 明细是否显示弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bomCode: null,
        bomName: null,
        productCode: null,
        status: null
      },
      // 表单参数
      form: {},
      // 明细表单参数
      detailForm: {},
      // 表单校验
      rules: {
        bomCode: [
          { required: true, message: "BOM编码不能为空", trigger: "blur" },
          { validator: this.validateBomCode, trigger: "blur" }
        ],
        bomName: [
          { required: true, message: "BOM名称不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "请选择产品", trigger: "change" }
        ]
      },
      // 明细表单校验
      detailRules: {
        materialId: [
          { required: true, message: "请选择物料", trigger: "change" }
        ],
        quantity: [
          { required: true, message: "用量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getMaterialList();
  },
  methods: {
    /** 查询BOM主表列表 */
    getList() {
      this.loading = true;
      listBom(this.queryParams).then(response => {
        this.bomList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bomId: null,
        bomCode: null,
        bomName: null,
        productId: null,
        productCode: null,
        productName: null,
        version: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
      this.activeTab = "basic";
      this.bomDetailList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.bomId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加BOM主表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bomId = row.bomId || this.ids
      getBom(bomId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改BOM主表";
        // 如果是修改，加载BOM明细
        if (this.form.bomId) {
          this.getBomDetailList(this.form.bomId);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.bomId != null) {
            updateBom(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBom(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bomIds = row.bomId || this.ids;
      this.$modal.confirm('是否确认删除BOM主表编号为"' + bomIds + '"的数据项？').then(function () {
        return delBom(bomIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`)
    },
    /** 校验BOM编码唯一性 */
    validateBomCode(rule, value, callback) {
      if (value) {
        checkBomCodeUnique({
          bomId: this.form.bomId,
          bomCode: value
        }).then(response => {
          callback();
        }).catch(error => {
          callback(new Error(error.msg));
        });
      } else {
        callback();
      }
    },
    /** 获取物料列表 */
    getMaterialList() {
      listMaterial({}).then(response => {
        this.materialList = response.rows || response.data || [];
      });
    },
    /** 处理产品选择变化 */
    handleProductChange(value) {
      if (value) {
        const selectedMaterial = this.materialList.find(item => item.materialId === value);
        if (selectedMaterial) {
          this.form.productCode = selectedMaterial.materialCode;
          this.form.productName = selectedMaterial.materialName;
        }
      } else {
        this.form.productCode = null;
        this.form.productName = null;
      }
    },
    
    // ========== BOM明细相关方法 ==========
    /** 获取BOM明细列表 */
    getBomDetailList(bomId) {
      getBomDetailByBomId(bomId).then(response => {
        this.bomDetailList = response.data || [];
      });
    },
    /** 明细多选框选中数据 */
    handleDetailSelectionChange(selection) {
      this.detailIds = selection.map(item => item.detailId);
      this.detailMultiple = !selection.length;
    },
    /** 新增明细按钮操作 */
    handleAddDetail() {
      this.resetDetailForm();
      this.detailOpen = true;
      this.detailTitle = "添加BOM明细";
    },
    /** 修改明细按钮操作 */
    handleUpdateDetail(row) {
      this.resetDetailForm();
      this.detailForm = { ...row };
      this.detailOpen = true;
      this.detailTitle = "修改BOM明细";
    },
    /** 删除明细按钮操作 */
    handleDeleteDetail(row) {
      const detailIds = row ? [row.detailId] : this.detailIds;
      this.$modal.confirm('是否确认删除选中的BOM明细？').then(() => {
        const promises = detailIds.map(id => delBomDetail(id));
        return Promise.all(promises);
      }).then(() => {
        this.getBomDetailList(this.form.bomId);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 明细表单重置 */
    resetDetailForm() {
      this.detailForm = {
        detailId: null,
        bomId: this.form.bomId,
        materialId: null,
        materialCode: null,
        materialName: null,
        materialSpec: null,
        materialUnit: null,
        quantity: null,
        sortNum: 1
      };
      this.resetForm("detailForm");
    },
    /** 明细取消按钮 */
    cancelDetail() {
      this.detailOpen = false;
      this.resetDetailForm();
    },
    /** 明细提交按钮 */
    submitDetailForm() {
      this.$refs["detailForm"].validate(valid => {
        if (valid) {
          if (this.detailForm.detailId != null) {
            updateBomDetail(this.detailForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.detailOpen = false;
              this.getBomDetailList(this.form.bomId);
            });
          } else {
            addBomDetail(this.detailForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.detailOpen = false;
              this.getBomDetailList(this.form.bomId);
            });
          }
        }
      });
    },
    /** 处理明细物料选择变化 */
    handleDetailMaterialChange(value) {
      if (value) {
        const selectedMaterial = this.materialList.find(item => item.materialId === value);
        if (selectedMaterial) {
          this.detailForm.materialCode = selectedMaterial.materialCode;
          this.detailForm.materialName = selectedMaterial.materialName;
          this.detailForm.materialSpec = selectedMaterial.specification;
          this.detailForm.materialUnit = selectedMaterial.unit;
        }
      } else {
        this.detailForm.materialCode = null;
        this.detailForm.materialName = null;
        this.detailForm.materialSpec = null;
        this.detailForm.materialUnit = null;
      }
    }
  }
};
</script>